package com.ow.dva.module.RoadPay;


import com.alipay.api.AlipayApiException;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.ow.dva.config.WXSCPayConfig;
import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.base.service.KafkaService;
import com.ow.dva.module.order.entity.Order;
import com.ow.dva.module.order.service.OrderService;
import com.ow.dva.module.park.entity.Road;
import com.ow.dva.module.park.service.ParkService;
import com.ow.dva.module.park.service.RoadService;
import com.ow.dva.module.terminal.service.TerminaService;
import com.ow.dva.util.pay.wxpay.HttpUtil;
import com.ow.dva.util.pay.wxpay.PayCommonUtil;
import com.ow.dva.util.pay.wxpay.RequestHandler;
import com.ow.dva.util.pay.wxpay.XMLUtil;
import org.jdom.JDOMException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/roadPay")
public class RoadPayController {
    @Resource
    private ParkService parkService;

    @Resource
    private TerminaService terminaService;

    @Resource
    private OrderService orderService;

    @Resource
    private KafkaService kafkaService;
    @Resource
    private RoadService roadService;

    /**
     * 扫描统一下单
     * @param request
     * @param response
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public void uniformOrder(HttpServletRequest request, HttpServletResponse response, Order order, String openId, ModelMap modelMap) throws JDOMException, IOException {
        System.out.println("--------------------扫描支付统一下单中(车道支付)-------------------------");
        String nonce_str = UUID.randomUUID().toString().replaceAll("-", "");
        //订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr(); //获取客户端的真是的IP
        // 订单号
        String out_trade_no = order.getId();
        Integer total_fee =1; //费用
//        Integer total_fee = (int)(order.getReallyMoney()*100);//TODO 总金额
        String body ="微信车道支付";
        //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", WXSCPayConfig.APPID);
        packageParams.put("mch_id", WXSCPayConfig.MCHID);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", total_fee+"");
        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url",WXSCPayConfig.CALLBACK_URL);
        packageParams.put("trade_type", "JSAPI");
        packageParams.put("openid", openId);
        System.out.println("回调路径"+WXSCPayConfig.CALLBACK_URL);
        //请求签名
        String sign = PayCommonUtil.createSign(WXSCPayConfig.CHARACTER, packageParams,WXSCPayConfig.WX_KEY);
        packageParams.put("sign", sign);
        //转换为xml格式的请求串
        String requestXML = PayCommonUtil.getRequestXml(packageParams);
//        //发送请求
        String resXml = HttpUtil.postData(WXSCPayConfig.MCH_URL, requestXML);
//        //返回内容转换为map
        Map map = XMLUtil.doXMLParse(resXml);
        String resultCode = (String) map.get("return_code");
        String prepay_id = (String) map.get("prepay_id");
        System.out.println("获取到的预支付ID："+ prepay_id);
        if("SUCCESS".equals(resultCode)){
            SortedMap<Object, Object> finalpackage = new TreeMap<Object, Object>();
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);;
            finalpackage.put("appId",map.get("appid"));//公众号id
            finalpackage.put("nonceStr",map.get("nonce_str")); // 支付签名随机串，不长于 32 位
            finalpackage.put("package","prepay_id=" + map.get("prepay_id")); // 支付签名随机串，不长于 32 位
            finalpackage.put("signType","MD5");
            finalpackage.put("timeStamp",timestamp);
            RequestHandler reqHandler = new RequestHandler(request, response);
            reqHandler.init(WXSCPayConfig.APPID,WXSCPayConfig.APPSECRET,WXSCPayConfig.WX_KEY);
            String finalsign = reqHandler.createSign(finalpackage);
            modelMap.put("appId",map.get("appid"));////公众号id
            modelMap.put("timeStamp", timestamp);//时间戳
            modelMap.put("nonceStr", map.get("nonce_str"));//随机字符串
            modelMap.put("packageValue","prepay_id=" + map.get("prepay_id"));//订单详情扩展字符串
            modelMap.put("paySign", finalsign);
        }
    }

    /**
     * 扫描后的确认订单页面
     * @return
     */
    @RequestMapping(value = "/confirmOrder", method = RequestMethod.GET)
    public String wxLogin(String id) {

        System.out.println("---------------------------网页授权-----------------------");
        String backUrl= WXSCPayConfig.URL+"/wechatPay/Back?id="+id;
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WXSCPayConfig.APPID
                + "&redirect_uri="+ URLEncoder.encode(backUrl)
                + "&response_type=code"
                + "&scope=snsapi_base"
                + "&state=STATE#wechat_redirect"
                + "&connect_redirect=1";
        return url;///必须重定向，否则不能成功
    }

    /**
     *
     * @param req
     * @param id
     * @param res
     * @param modelMap
     * @return
     */
    @RequestMapping("/Back")
    public  String  Back(HttpServletRequest req,String id,HttpServletResponse res,ModelMap modelMap) {
        System.out.println("---------------------------回调中-----------------------");
        String openid =getOpenid(req);
        System.out.println("---------------------------openId:"+openid+"-----------------------");
        if(openid!=null && !"".equals(openid)){
            Order order = confirmOrder(id);
            if(order !=null){
                try {
                    uniformOrder(req,res,order,openid,modelMap);
                } catch (JDOMException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            modelMap.put("order",order);
        }
        return  "/pay/road_index";
    }

    /**
     * 微信登录认证后的回调
     * @return
     */
    public  String  getOpenid(HttpServletRequest req){
        //start 获取微信用户基本信息
        String code =req.getParameter("code");
        String str="https://api.weixin.qq.com/sns/oauth2/access_token";
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", WXSCPayConfig.APPID);
        paramMap.put("secret", WXSCPayConfig.APPSECRET);
        paramMap.put("code", code);
        paramMap.put("grant_type", "authorization_code");
        String result= cn.hutool.http.HttpUtil.post(str, paramMap);
        try {
            Gson gson = new Gson();
            Map<String, Object> res   = gson.fromJson(result, new TypeToken<Map<String, Object>>() {}.getType());
            String openid=(String) res.get("openid");
            return  openid;
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            return  "";
        }
    }


    /**
     * 获取订单信息
     * @return
     */
    public  Order confirmOrder(String id){
        Order newOrder = null;
        Road road = roadService.getById(id);
        if (road != null){
            newOrder = orderService.selectNewOrderByRoad(id);
        }
        return  newOrder;
    }

    /**
     * 车道支付成功回调
     * @return
     */
    @RequestMapping("/WXpayCallBack")
    @ResponseBody
    public String WXpayCallBack(HttpServletRequest request)throws IOException{
        BufferedReader reader = request.getReader();
        String line = "";
        StringBuffer inputString = new StringBuffer();
        String result = null;
        try {
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            request.getReader().close();
            Map<String, String> restmap = XMLUtil.doXMLParse(inputString.toString());
            if("SUCCESS".equals(restmap.get("result_code"))){
                String out_trade_no = restmap.get("out_trade_no");
                Order order = orderService.getById(out_trade_no);
                if(order == null) return result;

                order.setOrderStatus(1);
                order.setPayType(2);
                orderService.updateById(order);
                if (order.getTerminalCode()!=null&&!"".equals(order.getTerminalCode())){
                    kafkaService.sendMessage(10,order.getTerminalCode(),order);
                }

                //订单支付成功推送消息
                try {
                    orderService.jpush(order,"3");
                }catch (Exception e){
                    e.printStackTrace();
                    System.out.println("推送消息异常！！");
                }
                result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     * @param id 车道id
     * @param request
     * @return
     */
    @RequestMapping("/roadPayScan")
    public String roadPayScan(String id, HttpServletRequest request) throws AlipayApiException {
        RT rt = orderService.isWxOrAli(request);
        if (rt.getMessage().equals("1")){//支付宝
            Order order = confirmOrder(id);
            String aliUrl = orderService.uniformOrder(order.getId());
            return "redirect:"+aliUrl;
        }else if(rt.getMessage().equals("2")) {//微信
            String url = wxLogin(id);
            return "redirect:"+url;///必须重定向，否则不能成功
        }else {
            return "未知来源";
        }
    }

}
